using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using MSOutlook = Microsoft.Office.Interop.Outlook;
using Utility = Microsoft.Sample.Outlook.Utility;

namespace Microsoft.Sample.Outlook.CRMIntegration.ItemForms
{
    internal sealed partial class ActivityForm : Form
	{

		Utility.ItemAdapter _activity;

		public ActivityForm()
		{
			InitializeComponent();
		}

		public ActivityForm(Utility.ItemAdapter item) 
		{
			InitializeComponent();
			if (item.Class != MSOutlook.OlObjectClass.olTask)
				throw new ApplicationException("ActivityForm can only be initalized with outlook task items");

			_activity = item;
		}

		public void CopyDataFromItem(Utility.ItemAdapter item)
		{
			if (item == null)
				return;

			if (item.Class == MSOutlook.OlObjectClass.olMail)
			{
				MSOutlook.MailItem mail = item.GetAsMail();

				this.textBoxComments.Text = mail.Body;
				this.textBoxName.Text = mail.Subject;
				this.comboBoxType.Text = "Inbox";
				this.comboBoxStatus.Text = "Not Started";
			}

			if (item.Class == MSOutlook.OlObjectClass.olAppointment)
			{
				MSOutlook.AppointmentItem appt = item.GetAsAppointment();

				this.textBoxComments.Text = appt.Body;
				this.textBoxName.Text = appt.Subject;
				this.comboBoxType.Text = "Meeting";
				this.comboBoxStatus.Text = "Not Started";
			}
		}

		private Guid? AccountFolderID
		{
			get
			{
				if (_activity == null)
					return null;

				MSOutlook.MAPIFolder folder = (MSOutlook.MAPIFolder)_activity.Parent;
				MSOutlook.MAPIFolder accountFolder = (MSOutlook.MAPIFolder)folder.Parent;

				CrmDataSetTableAdapters.AccountsTableAdapter accountsAdapter = new CrmDataSetTableAdapters.AccountsTableAdapter();
				return (Guid)accountsAdapter.GetLocalID(accountFolder.EntryID);
			}
		}

		private CrmDataSet.ActivitiesRow CurrentRow
		{
			get
			{
				DataRowView view = (DataRowView)activitiesBindingSource.Current;
				return (CrmDataSet.ActivitiesRow)view.Row;
			}
		}

		private void ActivityForm_Load(object sender, EventArgs e)
		{
			this.accountsTableAdapter.Fill(this.crmDataSet.Accounts);

			if (_activity == null)//new
			{
				activitiesBindingSource.AddNew();
				CurrentRow.LocalID = Guid.NewGuid();

				comboBoxAccount.Enabled = true;
			}
			else if (_activity.EntryID == null)
			{
				activitiesBindingSource.AddNew();
				CurrentRow.LocalID = Guid.NewGuid();
				comboBoxAccount.SelectedValue = AccountFolderID.Value; //get account id
			}
			else
			{
				this.activitiesTableAdapter.FillByOutlookID(this.crmDataSet.Activities, _activity.EntryID);
			}
		}
        

		private void btnSaveClose_Click(object sender, EventArgs e)
		{
            if (ValidateChildren() == false)
                return;

			activitiesBindingSource.EndEdit();

			CrmDataSet.ActivitiesRow row = this.CurrentRow;

			if (_activity == null)
			{
				string entryID = (string)accountsTableAdapter.GetOutlookID(row.AccountID);
				MSOutlook.MAPIFolder accountfolder = Globals.ThisApplication.Application.Session.GetFolderFromID(
					entryID, Globals.ThisApplication.Application.ActiveExplorer().CurrentFolder.StoreID);

				MSOutlook.MAPIFolder folder = Utility.Folder.GetFolder(accountfolder, Properties.Resources.ActivitiesFolderName);
				_activity = Utility.ItemAdapter.FromObject(folder.Items.Add(MSOutlook.OlItemType.olTaskItem));
			}

			if (Utility.SyncEngine.SyncItem<CrmDataSet.ActivitiesRow>(row, _activity, Utility.SyncDirection.ItemToOutlook))
				_activity.Save();

			if (CurrentRow.OutlookID != _activity.EntryID)
				CurrentRow.OutlookID = _activity.EntryID;

			int i = this.activitiesTableAdapter.Update(this.crmDataSet.Activities);
			if (associations != null)
				associations.Save();

			this.Close();
		}

		ActivityAssociationsControl associations = null;

		private void btnAssociations_Click(object sender, EventArgs e)
		{
			if (associations != null)
				return;


            Guid? accountID = AccountFolderID;
            if (accountID.HasValue == false)
            {
                if (comboBoxAccount.SelectedValue != null)
                    accountID = (Guid)comboBoxAccount.SelectedValue;
            }
			associations = new ActivityAssociationsControl(accountID, CurrentRow.LocalID);
			associations.Dock = DockStyle.Right;

			panelAssociations.Width = associations.Width;
			this.Width += associations.Width;
			panelAssociations.Controls.Add(associations);

            btnAssociations.Enabled = false;
		}

		private void comboBoxAccount_SelectedValueChanged(object sender, EventArgs e)
		{
			if (associations != null)
				associations.ChangeAccount((Guid)comboBoxAccount.SelectedValue);
		}

        private void textBoxName_Validating(object sender, CancelEventArgs e)
        {
            if (textBoxName.Text.Length > 0)
            {
                errorProvider.SetError(textBoxName, "");
                return;
            }
            
            errorProvider.SetError(textBoxName, "An Activity must have a name");
            e.Cancel = true;
        }

        private void comboBoxAccount_Validating(object sender, CancelEventArgs e)
        {
            if (comboBoxAccount.SelectedValue != null)
            {
                errorProvider.SetError(comboBoxAccount, "");
                return;
            }

            errorProvider.SetError(comboBoxAccount, "An account must be selected");
            e.Cancel = true;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }


	}
}